package com.cloudea.lotus.lambda;

import com.cloudea.lotus.Request;
import com.cloudea.lotus.Response;
import com.cloudea.lotus.dao.DAO;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class LotusLambdaImpl extends LotusLambda {

    private String objectName = "noObject";
    private DAO dao = null;

    public LotusLambdaImpl(String objectName, DAO dao){
        if(objectName != null && ! objectName.trim().equals("")){
            this.objectName = objectName;
        }
        this.dao = dao;
    }

    public void setObjectName(String objectName) {
        this.objectName = objectName;
    }

    public void setDao(DAO dao) {
        this.dao = dao;
    }

    public String getObjectName(){
        return this.objectName;
    }

    public DAO getDao(){
        return this.dao;
    }

    @Override
    public Response get(Request request) {
        String id = request.getId();
        if(!id.equals("")){
            JsonObject object =(dao.select(objectName, id));
            if(object == null){
                return Response.fail("查找不到此id的对象");
            }
            return Response.success(object);
        }
        // 读取列表
        JsonElement jsonElement = dao.select(objectName, request.getParameters());
        if(jsonElement == null){
            return  Response.fail("查询出现异常");
        }
        return Response.success(jsonElement);
    }

    @Override
    public Response post(Request request) {
        String generatedId = dao.insert(objectName, request.getParameters());
        if(generatedId == null){
            return Response.fail("添加失败");
        }
        return Response.success(generatedId);
    }

    @Override
    public Response put(Request request) {
        String id = request.getId();
        if(id.equals("")){
            return Response.fail("请输入id");
        }
        if(!dao.update(objectName, id, request.getParameters())){
            return Response.fail("更新失败");
        }
        return Response.success();
    }

    @Override
    public Response delete(Request request) {
        String id = request.getId();
        if(id.equals("")){
            return Response.fail("请输入id");
        }
        if(!dao.delete(objectName, id)){
            return Response.fail("删除失败");
        }
        return Response.success();
    }
}
